# -*- coding: utf-8 -*-
from typing import Dict, Any
from fastapi import HTTPException
from wechatpy.crypto import WeChatCrypto
from core.config import settings
from core.logger import log
from db.pydantic.request.qw_wh import QWPathParams, QWTextMessage, QWEventMessage
from services.customers import  create_customer_service
from services.redis_service import AsyncRedisService
from sqlalchemy.orm import Session
from utils.qw_util import get_qw_access_token, parse_message_local, get_event_msg, EventMessage
from utils.rag_api import get_reply_by_rag
from utils.sender_tools import SenderTools


def verify_body(body: bytes) -> bool:
    # 检查body是否为空
    if not body:
        log.error("接收到空的消息体")
        raise ValueError(f"缺少字段,数据为空")
    # 尝试解码为字符串
    try:
        body_str = body.decode('utf-8')
        log.info(f"解码后的消息内容: {body_str}")
        return True
    except Exception as e:
        log.error("在qw_router中的post/qw/webhook方法，非法的请求体参数", e)
        raise HTTPException(status_code=400, detail="Invalid XML")

def decrypt_message(body_str: str, msg_signature: str,timestamp,nonce):
    crypto = WeChatCrypto(settings.QW_TOKEN, settings.QW_SECRET, settings.QW_APP_ID)
    try:
        decrypted_xml = crypto.decrypt_message(
            body_str,
            msg_signature,
            timestamp,
            nonce
        )
        log.info(f"解密后的明文消息xml内容: {decrypted_xml}")
        msg = parse_message_local(decrypted_xml)
        log.info(f"解密后的明文消息内容: {msg}")
        log.info(f"解密后的明文类型: {type(msg)}")
        return msg
    except Exception as e:
        # 处理异常或忽略
        raise HTTPException(status_code=400, detail="解密失败")


def _parse_text_message(msg: Dict[str, Any])->QWTextMessage:

    """
    {
			"msgid": "ABwvH3MWEJJHF9JM1wWyJcLBoR",
			"open_kfid": "wknfhmZgAAiQrJ5oBNmll5c7B9YU6fhw",
			"external_userid": "wmnfhmZgAApQfPdhoFWqTHK2JDj5gR3A",
			"send_time": 1758100722,
			"origin": 3,
			"msgtype": "text",
			"text": {
				"content": "哦哦哦亲"
			}
		}
    """
    content = msg["text"]["content"]
    external_userid: str = msg["external_userid"]
    origin = msg["origin"]
    msg_id = msg["msgid"]
    msg_type = msg["msgtype"]
    create_time = msg["send_time"]

    msg = {
        "msg_type": msg_type,
        "content": content,
        "msg_id":msg_id,
        "create_time":create_time,
        "external_userid":external_userid,
        "origin":origin,
        "open_kfid":msg["open_kfid"]
    }
    return QWTextMessage(**msg)
def _parse_event_message(msg: Dict[str, Any])->QWEventMessage:
    """
        {
    			"msgid": "4FET4YrQZLvtoU39DD47J3sCH2hBiMeC6rhTjQKawh1Q",
    			"send_time": 1758100594,
    			"origin": 4,
    			"msgtype": "event",
    			"event": {
    				"event_type": "enter_session",
    				"scene": "",
    				"open_kfid": "wknfhmZgAAiQrJ5oBNmll5c7B9YU6fhw",
    				"external_userid": "wmnfhmZgAAP3ba7cWykiOr7rxNHD6Feg"
    			}
    		},
        """
    msg={
        "msg_id":msg["msgid"],
        "external_userid":msg["event"]["external_userid"],
        "event_type":msg["event"]["event_type"],
        "create_time":msg["send_time"],
        "origin": msg["origin"],
        "msgtype": msg["msgtype"],
        "open_kfid": msg["event"]["open_kfid"],
        "scene": msg["event"]["scene"] if msg["event"]["scene"] else None,
        "scene_param": msg["event"].get("scene_param", None),
        "welcome_code": msg["event"].get("welcome_code", None)
    }
    log.info(f"event解析后的消息内容----->: {msg}")
    return QWEventMessage(**msg)


async def process_message(body:bytes,qw_req:QWPathParams, redis_service:AsyncRedisService, sender_tools:SenderTools,db:Session):
    if not verify_body(body):
        raise HTTPException(status_code=503, detail="校验失败...")
    # 解密消息,返回明文数据
    msg = decrypt_message(body.decode('utf-8'),qw_req.msg_signature,qw_req.timestamp,qw_req.nonce)

    # 解析消息 预处理，将消息统一格式
    messages_dict:dict[str, Any] = await _first_process_msg(msg,redis_service)
    if not messages_dict:
        return
    text_msgs:list[QWTextMessage] = messages_dict["text_msgs"]
    event_msgs:list[QWEventMessage] = messages_dict["event_msgs"]
    """测试发送消息"""
    for msg in text_msgs:
        log.info(f"文本消息: {msg}")

        # 将特定的一些消息进行提前处理--> 例如：怎么查不动产----不走模型,直接发送文件
        # if await fiter_special_chat(msg.content,msg.external_userid):
        #     continue
        await _process_custom_msg(msg=msg, redis_service=redis_service,sender_tools=sender_tools)
    for msg in event_msgs:
        await _process_event_msg(msg,redis_service,sender_tools,db)



async def _first_process_msg(msg,redis_service:AsyncRedisService)-> dict:
    # 解析消息 消息预处理，将消息统一格式
    processed_data = {}
    if isinstance(msg, EventMessage):
        msg_list:list = await get_event_msg(msg,redis_service)
        if msg_list is None:
            raise ValueError("消息数据为空")
        text_msgs = [_parse_text_message(msg) for msg in msg_list if msg["msgtype"]=="text"]
        event_msgs = [_parse_event_message(msg) for msg in msg_list if msg["msgtype"]=="event"]
        processed_data["text_msgs"] = text_msgs
        processed_data["event_msgs"] = event_msgs
    return processed_data



async def _process_custom_msg(msg:QWTextMessage,redis_service:AsyncRedisService, sender_tools:SenderTools):
    # 开始回复
    # reply = await get_reply_by_rag(msg.content, msg.external_userid, msg.open_kfid)
    # access_token = await get_qw_access_token()
    # if "回电话" in reply:
    #     # history_msgs = await get_wx_messages_by_session_id(sender_id=msg.from_user, receiver_id=msg.to_user)
    #     # result = await generate_description(history_msgs)
    #     # await set_friends_remark(msg.to_user, msg.from_user, result)
    #
    #     # link = await get_business_card_link(msg.external_userid)
    #     link = "https://work.weixin.qq.com/ca/cawcde72304ee0ca45"
    #     sender_tools.send_qw_business_card(access_token, msg.external_userid, msg.open_kfid, link)
    #     sender_tools.send_qw_messages(access_token, msg.external_userid, msg.open_kfid, "这个是您的专属客户经理，点击添加为好友")
    #     return
    #
    # send = sender_tools.send_qw_messages(access_token, msg.external_userid, msg.open_kfid, reply)

    # log.info(f"发送结果: {send}")
    pass


async def _process_event_msg(msg:QWEventMessage,redis_service:AsyncRedisService, sender_tools:SenderTools,db:Session):
    if msg.event_type == "enter_session":
        log.info(f"用户进入会话: {msg}")
        # log.info(f"scene值 为: {msg.scene}")
        # data = {
        #     "phone": msg.scene,
        #     "source": "sms",
        #     "customer_name": "未知",
        #     "external_id":msg.external_userid
        # }
        # res = await create_customer_service(customer_data=data,db=db)
        # if res.code==200:
        #     log.info(f"创建客户成功: {res.data}")
        # else:
        #     log.error(f"创建客户失败: {res.msg}")
        if msg.welcome_code:
            access_token = await get_qw_access_token()
            sender_tools.send_qw_welcome_message(access_token, msg.welcome_code,msg.external_userid,msg.open_kfid)







